package org.sixtynine.stock.dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.sixtynine.stock.Constants;
import org.sixtynine.stock.dao.AspiDataDao;
import org.sixtynine.stock.dto.GridPramDTO;
import org.sixtynine.stock.dto.Page;
import org.sixtynine.stock.entity.AspiData;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class AspiDataDaoImpl extends AbstractDaoImpl<AspiData, Integer>
		implements AspiDataDao {

	protected AspiDataDaoImpl() {
		super(AspiData.class);
	}

	@Override
	public void saveAspiData(AspiData aspiData) {
		saveOrUpdate(aspiData);

	}

	@Override
	public List<AspiData> findAspiData(Date aspiDataDate) {
		return findByCriteria(Restrictions.eq("date", aspiDataDate));
	}

	@Override
	public List<AspiData> searchMonthlyAspiData(Date fromDate, Date toDate,
			String orderBy) {
		Criteria criteria = getCurrentSession().createCriteria(AspiData.class);

		criteria.addOrder(Order.desc(getRecordOrder(orderBy)));

		if (fromDate != null) {
			criteria.add(Restrictions.ge("date", fromDate));
		}

		if (toDate != null) {
			criteria.add(Restrictions.le("date", toDate));
		}

		return findByCriteria(criteria);
	}

	@Override
	public Page<AspiData> searchMonthlyAspiData(Date fromDate, Date toDate,
			String orderBy, GridPramDTO gridPramDTO) {
		Criteria criteria = getCurrentSession().createCriteria(AspiData.class);

		criteria.addOrder(Order.desc(getRecordOrder(orderBy)));

		if (fromDate != null) {
			criteria.add(Restrictions.ge("date", fromDate));
		}

		if (toDate != null) {
			criteria.add(Restrictions.le("date", toDate));
		}

		return findByCriteria(criteria, gridPramDTO);
	}

	@Override
	@Transactional
	public void deleteAspiData(Date fromDate, Date toDate) {
		String sql = "delete from AspiData where 1=1 ";

		if (fromDate != null) {
			sql += "and date >= :fromData ";
		}
		if (toDate != null) {
			sql += "and date <= :toDate ";
		}

		Query query = getCurrentSession().createQuery(sql);
		if (fromDate != null) {
			query.setParameter("fromDate", fromDate);
		}
		if (toDate != null) {
			query.setParameter("toDate", toDate);
		}

		query.executeUpdate();

	}

}
